package com.steptime.thread.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 演示 AtomicInteger的基本用法，对比非原子类的线程
 * 安全问题，使用了原子类之后，不需要加锁，也可以保证线程安全。
 */
public class AtomicIntergerDemo implements Runnable{

    private  AtomicInteger atomicInterger = new AtomicInteger();
    private  Integer basicInteger = 0;

    private  void incrementAtomic(){
        atomicInterger.getAndIncrement();
    }

    private  void incrementBasic(){
        basicInteger++;
    }

    public static void main(String[] args) {
        AtomicIntergerDemo atomicIntergerDemo = new AtomicIntergerDemo();
        Thread thread1 = new Thread(atomicIntergerDemo);
        Thread thread2 = new Thread(atomicIntergerDemo);
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("原子类自增结果："+atomicIntergerDemo.atomicInterger);
        System.out.println("非线程安全的自增结果(每次结果都不一样)："+atomicIntergerDemo.basicInteger);
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            incrementAtomic();
            incrementBasic();
        }
    }
}
